package pl.minim.unidefCMS.objects {
	import pl.minim.unidefCMS.UnidefManager;
	
	import com.googlecode.milib.util.MLArrayUtil;	

	/**
	 * @author Marek Brun
	 */
	public class UnidefPredefined extends AbstractUnidefObject {
		
		public var clazz:String;		private var selectedObj:AbstractUnidefObject;

		public function UnidefPredefined(clazz:String, manager:UnidefManager) {
			this.clazz=clazz;
			this.manager=manager;
			
		}
		
		override public function getTypeName():String {
			return 'Predefined';
		}
		
		public function getObjectsToSelect():Array {
			return manager.getPredefinedList(clazz);
		}
		
		public function getSelectedObj():AbstractUnidefObject {
			return selectedObj;
		}
		
		public function setSelectedObj(unidef:AbstractUnidefObject):void {
			selectedObj=unidef;
		}
		
		public function setChoosedObjByID(id:String):void {
			setSelectedObj(manager.getPredefined(clazz, id));
		}
		
		public function removeObj(unidef:UnidefClass):void {
			var objs:Array=getObjectsToSelect();
			if(getSelectedObj()==unidef){
				setSelectedObj(AbstractUnidefObject(MLArrayUtil.getNextByValue(objs, unidef)));
			}
			manager.removePredefinedObj(clazz, unidef);
		}
		
		override public function getDataAsTextPreview():String {
			if(selectedObj){
				return selectedObj.id;
			}
			return '';
		}
		
		override public function toXML():XML {
			var xml:XML=<i/>;
			if(selectedObj){
				xml.appendChild(selectedObj.id);
			}
			return xml;
		}
		
		override public function reactToPredefinedObjectDelete(deletedObject:UnidefClass):void {
			if(selectedObj==deletedObject){
				var objs:Array=getObjectsToSelect();
				if(objs.length>0){
					selectedObj=objs[0];
				}else{
					selectedObj=null;
				}
			}
		}
		
		override public function exportToRawData():* {
			if(!selectedObj){
				return null;
			}
			return selectedObj.exportToRawData();
		}
		
	}
}
/*

<item type="class" id="clients">
	<item type="txt" id="name" editLines="1"/>
	<item type="url" id="link"/>
</item>

*/